import {transformI18n} from "@/plugins/i18n";
import type {PaginationProps} from "@pureadmin/table";
import {OrderTongji,setDiyPercent} from "@/api/statistics";
import {getSalesList} from "@/api/crm";
import * as XLSX from 'xlsx'

import {CopyDocument} from '@element-plus/icons-vue'
import {onMounted, reactive, ref, type Ref, toRaw} from "vue";
import {hasPerms} from "@/utils/auth";

export function useAccount(tableRef: Ref) {
  const form = reactive({
    utm_source: "",
    tab_id: "0",
    search_field2: "default",
    audit_status: "3",time:[]
  });
  const curRow = ref();
  const dataList = ref([]);
  const statusList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const salesman_arr = ref([]);



  const exportExcel = () => {
    try {
      const tableEl = tableRef.value.$el
      // 克隆表格（避免影响原表格）
      const clonedTable = tableEl.cloneNode(true)
      // 处理模板内容（转换为纯文本）
      const processTemplates = (node) => {
        // 处理el-tag
        const tags = node.querySelectorAll('.el-tag')
        tags.forEach(tag => {
          tag.outerHTML = tag.textContent
        })
        // 处理el-switch
        const switches = node.querySelectorAll('.el-switch')
        switches.forEach(sw => {
          const isActive = sw.querySelector('.is-active')
          sw.outerHTML = isActive ? '启用' : '禁用'
        })
        // 处理自定义内容（如头像+文本）
        const customContents = node.querySelectorAll('.el-avatar')
        customContents.forEach(avatar => {
          const parent = avatar.parentNode
          parent.outerHTML = parent.textContent.replace(/\s+/g, ' ').trim()
        })

        // 移除操作按钮等不需要的元素
        const buttons = node.querySelectorAll('.el-button')
        buttons.forEach(btn => btn.remove())
      }
      processTemplates(clonedTable)
      // 转换为工作表
      const ws = XLSX.utils.table_to_sheet(clonedTable)
      // 创建工作簿并导出
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      XLSX.writeFile(wb, '统计_'+form.tab_id+'_'+form.time+'.xlsx')
    } catch (error) {
      console.error('导出失败:', error)
    } finally {
    }
  };

  const perms = {
    set_bili: hasPerms('user:btn:set_bili')//设置自定义比例
  };

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    { label: "id", prop: "id", width: 80, align: "left"},
    {label: "类别", prop: "type",width:130,showOverflowTooltip:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"+row.color):''}>{row.type}</span>
      )},
    {label: "类名", prop: "name",width:120,showOverflowTooltip:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"+row.color):''}>{row.name}</span>
      )},
    {label: "业绩目标", prop: "sales_target", width: 100,sortable:true,hide:() => form.tab_id=='3',cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"+row.color):''}>{row.sales_target}</span>
      )},
    {label: "业绩占比", prop: "sales_target_bili", width: 100,sortable:true,hide:() => form.tab_id=='3',cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"+row.color):''}>{(row.sales_target_bili||0).toFixed(2)}%</span>
      )},
    {label: "待处理自定义占比", prop: "diy_bili", minWidth: 220,sortable:true, hide:() => form.tab_id=='3',cellRenderer: ({ row, index }) => (
        perms.set_bili&&row.name!=='未分配' ? <div className="diy_bili">
          <el-slider v-model={row.diy_bili} size="small" step={0.01} onChange={(v) => handleSliderChange(v)}/><el-input style="width:38px" v-model={row.diy_bili}/>%</div> : null
      )},
    {label: "弃单自定义占比", prop: "diy_bili_qidan", minWidth: 220,sortable:true, hide:() => form.tab_id=='3',cellRenderer: ({ row, index }) => (
        perms.set_bili&&row.name!=='未分配' ? <div className="diy_bili_qidan">
          <el-slider v-model={row.diy_bili_qidan} size="small" step={0.01} onChange={(v) => handleSliderChange(v)}/><el-input style="width:38px" v-model={row.diy_bili_qidan}/>%</div> : null
      )},
    {label: "总数", prop: "count", width: 100,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"+row.color):''}>{row.count}</span>
      )},
    {label: "未分配", prop: "no", width: 100,sortable:true},
    {label: "待处理订单数", prop: "finished", width: 120,sortable:true,cellRenderer: ({ row, index }) => (
        (row.finished_list!=undefined&&row.finished>0)?<>
           <el-icon v-copy:click={row.finished_list.join("\r\n")}><CopyDocument /></el-icon>
           <el-tooltip content={row.finished_list.join("<br/>")} placement="bottom" raw-content effect="light">
             <span style={row.color?("font-weight: bold;color:"):''}>{row.finished}</span>
           </el-tooltip>
         </>:
        <span style={row.color?("font-weight: bold;color:"):''}>{row.finished}</span>
      )},
    {label: "待处理应得", prop: "yingde_finished", width: 120,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.yingde_finished}</span>
      )},
    {label: "待处理待补", prop: "daibu", width: 120,sortable:true,className:'daibu_tips',cellRenderer: ({ row, index }) => (
        <span style={"font-weight: bold;color:"+((row?.yingde_finished||0)>row.finished?'green':'red')}>{(row?.yingde_finished||0)>0?(row.yingde_finished-row.finished):0}</span>
      )},
    {label: "弃单数", prop: "qidan", width: 100,sortable:true,cellRenderer: ({ row, index }) => (
        (row.qidan_list!=undefined&&row.qidan>0)?<>
          <el-icon v-copy:click={row.qidan_list.join("\r\n")}><CopyDocument /></el-icon>
          <el-tooltip content={row.qidan_list.join("<br/>")} placement="bottom" raw-content effect="light">
            <span style={row.color?("font-weight: bold;color:"):''}>{row.qidan}</span>
          </el-tooltip>
        </>:
        <span style={row.color?("font-weight: bold;color:"):''}>{row.qidan}</span>
      )},
    {label: "弃单应得", prop: "yingde_qidan", width: 100,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.yingde_qidan}</span>
      )},
    {label: "弃单待补", prop: "daibu", width: 100,sortable:true,className:'daibu_tips',cellRenderer: ({ row, index }) => (
        <span style={"font-weight: bold;color:"+((row?.yingde_qidan||0)>row.qidan?'green':'red')}>{(row?.yingde_qidan||0)>0?(row.yingde_qidan-row.qidan):0}</span>
      )},
  ];
  const diyBiliChangeAble = ref(false)
  function handleSliderChange(v) {
    diyBiliChangeAble.value = true
  }

  //保存设置的自定义比例
  async function handleSaveDiyBili(){
    await setDiyPercent(toRaw({list:ApiData.value}), 'post');
    onSearch();
  }

  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  const today = new Date();
  const last30Days = new Date(today);
  last30Days.setDate(today.getDate() - 29);
  // form.time = [formatDate(last30Days),formatDate(today)]
  form.time = [formatDate(today),formatDate(today)]

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }
  const getSalemanList = async function (page=1,limit=1000) {
    const {data} = await getSalesList({page,limit}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    salesman_arr.value = data?.data;
  }
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  const ApiData = ref([]);
  async function onSearch() {
    loading.value = true;
    // form.page = pagination.currentPage
    // form.limit = pagination.pageSize
    const {data} = await OrderTongji(toRaw(form), 'get');
    ApiData.value = data.list;
    dataList.value = data.list[0];
    filterData()
    // statusList.value = data.status_arr;
    // searchCondList.value = data?.search_cond_arr;
    // pagination.total = data.total;
    // pagination.pageSize = data.per_page;
    // pagination.currentPage = data.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  function filterData(){
    dataList.value = ApiData.value[form.tab_id]||[];
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };


  /** 数据权限 可自行开发 */
  const searchCondList =  ref([])


  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    getSalemanList();
  });

  return {
    form, isShow, curRow, loading, columns, dataList, isLinkage, pagination, isExpandAll, isSelectAll,
    statusList,salesman_arr,exportExcel,
    onSearch, resetForm,filterData,
    searchCondList,diyBiliChangeAble,handleSaveDiyBili,
     filterMethod, transformI18n, handleSizeChange,
    handleCurrentChange
  };
}
